package org.stvd.common.utils;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.net.util.Base64;


/**
 * Des加密工具类
 * @author houzx
 */
public class DesUtil {
	
	public static void main(String[] args) throws Exception {
    	String key = "nmbt1324";
    	String value = "13011523654";
    	System.out.println("加密内容："+value);
    	System.out.println("密钥："+key);
    	
    	String a=GZipUtil.gzipString(encrypt(value, key).toUpperCase());

    	System.out.println("加密后的数据为:"+a);
    	//c# 密码
    	String ckey="262AF5ED25DCCA09BB2D9B20AB50A34A6540533145D33B0C61A2A7325218525E3D1F1418BE4697BE655E9690A523A6888755E62244417F150C1608D6C4B9F0DF25C8AA73759BC361291C43491E40BD03D8DD3777D5EB745BB99598FCFBA690575F06A42EB2B6EA32254185A771006E32E2D15" +
    			"2122028CF8517248D487E489A9734FD7F6CA04B4D54";
    	if (a.equals(ckey)) {
			System.out.println("与C#相同 ok");
		}else {
			System.out.println("与C#不同 err");
		}
    	//String aa = "399A01EFFDCBF95DB8CEB846F7B8E48869248979D49D10D670E5C0B5449D463CE992A9130CA882ECC0A58A37D84A31A728E6D038C4A91EA8929CBC128DEBAAFED3257FBA52E9DCACE1A9E851F3D0C4FBBF5394F6985EC9CA271C976AFCDB930F3A88155C09C0735007BE9B7409F4712884DB4BC1B2AF63ECDFBBB579FDD4D42539E6CE2A394498D16BD2F4EB391395370E47B06F6305BA43D4972BD8853B176A88486F93436C9B0781CA993D0FC5C06677E49EF9E97AE767DA26C5F3487FCBC4B4B788E68D71DB056AAE8D85DC75C3C3DAA48A4C6DA0674ACA4CDEF8A105C259ABE78CD19FDDED06B763102116EFFF1C";
    	//String b=java.net.URLDecoder.decode(decrypt(aa,key), "utf-8") ;
    	String b = decrypt(GZipUtil.ungzipString(a),key);
    	if (b.equals(value)) {

        	System.out.println("===========加密成功==============="); 
		}else {

	    	System.out.println("============加密失败===================="); 
		}
    	System.out.println("解密后的数据:"+b); 

    }

	/**
	 * DES加密
	 * @parameter message：需要加密的消息
	 * @parameter key：秘钥
	 * @return   加密后的字符串
	 */
	public static String encrypt(String message, String key) throws Exception {
		//对字符串进行URL编码
//		String jiami=java.net.URLEncoder.encode(message, "utf-8").toLowerCase();
		String jiami=java.net.URLEncoder.encode(message, "utf-8");
		jiami=encryptBASE64(jiami);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		byte[] bs=cipher.doFinal(jiami.getBytes("UTF-8"));
		return toHexString(bs);
//		return toHexString(bs).toUpperCase();
	}
	
	/**
	 * DES解密
	 * @parameter message：需要解密的消息
	 * @parameter key：秘钥
	 * @return   解密后的字符串
	 */
	public static String decrypt(String message,String key) throws Exception {
		byte[] bytesrc =convertHexString(message); 
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		byte[] retByte = cipher.doFinal(bytesrc);
		String ret = new String(retByte,"UTF-8"); 
		//先以base64进行解密，然后用URL进行解码
//		ret = java.net.URLDecoder.decode(decryptBASE64(ret).toLowerCase(),"utf-8");
		ret = java.net.URLDecoder.decode(decryptBASE64(ret),"utf-8");
		return ret;
	}


	public static byte[] convertHexString(String ss)
	{
		byte digest[] = new byte[ss.length() / 2];
		for(int i = 0; i < digest.length; i++)
		{
			String byteString = ss.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte)byteValue;
		}
		return digest;
	}
	
    public static String toHexString(byte b[]) {
    	StringBuffer hexString = new StringBuffer();
    	for (int i = 0; i < b.length; i++) {
    		String plainText = Integer.toHexString(0xff & b[i]);
    		if (plainText.length() < 2)
    			plainText = "0" + plainText;
    		hexString.append(plainText);
    	}
    	return hexString.toString();
    } 
	
    /**
	 * 以base64对字符串加密
	 * @param s
	 * @return
	 */
	public static String encryptBASE64(String s) {
		String ret = "";
		byte[] b=s.getBytes();
		try {
			ret = new String(Base64.encodeBase64(b), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ret;
	}
	/**
	 * 以base64对字符串解密
	 * @param s
	 * @return
	 */
	public static String  decryptBASE64(String s) {
		byte[] ret = {};
		try {
			ret = Base64.decodeBase64(s.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			return  new String(ret,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
    
	/**
	 * Des(Base64(flatid),密钥),先进行base64加密，再进行des加密
	 * @param source
	 * @param key
	 * @return
	 * @throws Exception 
	 */
	public static String encryptDesBase64(String source,String key) throws Exception{
		String base64Str = encryptBASE64(source) ;
		System.out.println("base64Str : " + base64Str);
		String desStr = encrypt(base64Str,key);
		System.out.println("desStr : " + desStr);
		return desStr ;
	}

	/**
	 * Des(Base64(flatid),密钥),先进行des解密，在进行base64解密
	 * @param source
	 * @param key
	 * @return
	 * @throws Exception 
	 */
	public static String decryptDesBase64(String source,String key) throws Exception{
		
		String base64Str = encryptBASE64(source) ;
		System.out.println("base64Str : " + base64Str);
		String desStr = decrypt(source,key);
		System.out.println("desStr : " + desStr);
		return base64Str ;
//		return decryptBASE64(decrypt(source,key));
	}

}